let pointCollection = []
let typhoonCollection = []
let graphicLayer = null
let landList = []
let brandMap = new Map()
// let currentShow = null
export default {
	start: function(viewer, dataList, fllow, callback) {
		const typhoonName = dataList.name || '台风'
		let result = []
		landList = dataList.land
		const points = dataList.points
		for (let p = 0; p < points.length; p++) {
			const d = {
				FID: points[p].time, // 时间
				serial: p + 1,
				fLongitude: points[p].lng,
				fLatitude: points[p].lat,
				speed: points[p].speed, // 风力
				power: points[p].power, // 风速
				strong: points[p].strong, // 气压类型
				pressure: points[p].pressure, // 中心气压
				movespeed: points[p].movespeed, // 移速
				movedirection: points[p].movedirection, // 移动方向
				radius7: points[p].radius7, // 七级半径
				radius10: points[p].radius10, // 十级半径
				radius12: points[p].radius12, // 十二级半径
			}
			result.push(d)
		}
		typhoonFlytoPath(viewer, result, typhoonName, fllow)
		viewer.screenSpaceEventHandler.setInputAction((movement) => {
			let pickedFeature = viewer.scene.pick(movement.endPosition)
			// if (currentShow) currentShow.visible = false
			if (pickedFeature) {
				// currentShow = brandMap.get(pickedFeature.id.id)
				// if (currentShow) currentShow.visible = true
				if (pickedFeature.id && pickedFeature.id.posInfo) {
					callback(pickedFeature.id)
				}

				return
			} else {
				callback(null)
			}
		}, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
	},
	destory: function() {
		destroyed()
	},
}

function typhoonFlytoPath(viewer, positions, typhoonName, fllow) {
	// 允许飞行动画
	viewer.clock.shouldAnimate = true
	viewer.clock.canAnimate = false
	// 设定模拟时间的界限
	const start = Cesium.JulianDate.fromDate(new Date(2020, 7, 1, 16))
	const stop = Cesium.JulianDate.addSeconds(start, positions.length, new Cesium.JulianDate())

	viewer.clock.startTime = start.clone()
	viewer.clock.stopTime = stop.clone()
	viewer.clock.currentTime = start.clone()
	viewer.clock.clockRange = Cesium.ClockRange.CLAMPED // UNBOUNDED;//单次循环 // LOOP_STOP; //末尾循环
	// 飞行速度，值越大速度越快，multiplier为0停止移动
	viewer.clock.multiplier = 3
	// viewer.timeline.zoomTo(start, stop);

	// 计算飞行时间和位置
	const property = computeFlight(start, positions, typhoonName)

	let rotation = Cesium.Math.toRadians(30)

	function getRotationValue() {
		rotation += -0.03
		return rotation
	}
	const typhoonEntity = viewer.entities.add({
		name: '台风路径',
		availability: new Cesium.TimeIntervalCollection([
			new Cesium.TimeInterval({
				start: start,
				stop: stop,
			}),
		]),
		position: property,
		orientation: new Cesium.VelocityOrientationProperty(property), // 根据位置移动自动计算方向
		ellipse: {
			semiMinorAxis: 35000.0,
			semiMajorAxis: 35000.0,
			height: 0.0,
			fill: true,
			outlineColor: Cesium.Color.RED,
			outlineWidth: 5,
			outline: false,
			rotation: new Cesium.CallbackProperty(getRotationValue, false),
			stRotation: new Cesium.CallbackProperty(getRotationValue, false),
			material: new Cesium.ImageMaterialProperty({
				image: '/images/typhoon.gif',
				transparent: true,
			}),
		},
		point: {
			pixelSize: 10,
			color: Cesium.Color.TRANSPARENT,
			outlineColor: Cesium.Color.YELLOW,
			outlineWidth: 4,
		},
		label: {
			text: typhoonName,
			font: '18px sans-serif',
			pixelOffset: new Cesium.Cartesian2(0.0, -50),
		},
	})
	let pathPosition = [Cesium.Cartesian3.fromDegrees(0, 0), Cesium.Cartesian3.fromDegrees(1, 0)]
	let pathEntity = viewer.entities.add({
		polyline: {
			positions: new Cesium.CallbackProperty(function() {
				return pathPosition
			}, false),
			material: new Cesium.PolylineGlowMaterialProperty({
				glowPower: 0.9,
				color: Cesium.Color.YELLOW,
			}),
			width: 3,
			clampToGround: true,
		},
	})
	let bool = true
	setAnimation((timer) => {
		let currentPosition = property.getValue(viewer.clock.currentTime)
		if (currentPosition === undefined) {
			clearAnimation(timer)
			return
		}
		pointCollection.map((point) => {
			if (!point.show && point.id <= viewer.clock.currentTime.secondsOfDay) {
				point.show = true
			}
		})
		if (currentPosition) {
			if (bool) {
				pathPosition = [currentPosition]
				bool = false
			}
			if (pathPosition.length > 5 && currentPosition.equals(pathPosition[pathPosition.length - 1]) && currentPosition.equals(pathPosition[pathPosition.length - 2])) {
				clearAnimation(timer)
				return
			}
			pathPosition.push(currentPosition)
		}
	}, 50)
	// 设置飞行视角
	viewer.trackedEntity = undefined

	// viewer.flyTo(typhoonEntity, {
	// 	duration: 2,
	// 	offset: {
	// 		heading: Cesium.Math.toRadians(359.9999999999998),
	// 		pitch: Cesium.Math.toRadians(-89.9515264956849),
	// 		// heading: Cesium.Math.toRadians(0.0),
	//         // pitch: Cesium.Math.toRadians(-90),
	//         //range: 1500000,

	// 	},
	// })

	viewer.camera.flyTo({
		destination: Cesium.Cartesian3.fromDegrees(123.89487301827336, 30.948157510717145, 4763825.001339431),
		orientation: {
			heading: 0.000050673509669252326,
			pitch: -1.5539662604596298,
			roll: 0,
		},
		duration: 1,
	})

	// 设置线性插值算法
	typhoonEntity.position.setInterpolationOptions({
		interpolationDegree: 3,
		interpolationAlgorithm: Cesium.LinearApproximation, // LagrangePolynomialApproximation
	})

	// 飞行视角追踪
	if (fllow) {
		let preUpdateHandler = function() {
			if (typhoonEntity) {
				const center = typhoonEntity.position.getValue(viewer.clock.currentTime)
				const hpr = new Cesium.HeadingPitchRange(Cesium.Math.toRadians(0.0), Cesium.Math.toRadians(-90), 1500000)
				if (center) {
					viewer.camera.lookAt(center, hpr)
				}
			}
		}
		viewer.scene.preUpdate.addEventListener(preUpdateHandler)
	}
	typhoonCollection.push(pathEntity)
	typhoonCollection.push(typhoonEntity)
}

function computeFlight(start, positions, typhoonName) {
	const property = new Cesium.SampledPositionProperty()
	for (let i = 0; i < positions.length; i++) {
		const time = Cesium.JulianDate.addSeconds(start, i, new Cesium.JulianDate())
		const Color = setcolor(positions[i].power)
		const position = Cesium.Cartesian3.fromDegrees(parseFloat(positions[i].fLongitude), parseFloat(positions[i].fLatitude), Cesium.Math.nextRandomNumber() * 500 + 1750)
		property.addSample(time, position)
		// addInfoBrand(time.secondsOfDay, positions[i], typhoonName)
		const point = viewer.entities.add({
			name: positions[i].serial,
			id: time.secondsOfDay,
			position: position,
			show: false,
			point: {
				pixelSize: 10,
				color: Color,
				scale: 1,
			},
		})

		point.posInfo = positions[i]
		point.typhoonName = typhoonName

		typhoonCollection.push(point)
		pointCollection.push(point)
	}
	property.forwardExtrapolationType = Cesium.ExtrapolationType.EXTRAPOLATE // 'ExtrapolationType.HOLD';
	return property
}

function setcolor(state) {
	if (state >= 16) {
		return Cesium.Color.RED
	} else if (state >= 14) {
		return Cesium.Color.PURPLE
	} else if (state >= 12) {
		return Cesium.Color.ORANGE
	} else if (state >= 10) {
		return Cesium.Color.YELLOW
	} else if (state >= 8) {
		return Cesium.Color.BLUE
	} else {
		return Cesium.Color.GREEN
	}
}

function setAnimation(callback, interval) {
	let timer
	const now = Date.now
	let startTime = now()
	let endTime = startTime
	const loop = () => {
		timer = window.requestAnimationFrame(loop)
		endTime = now()
		if (endTime - startTime >= interval) {
			startTime = endTime = now()
			callback(timer)
		}
	}
	timer = window.requestAnimationFrame(loop)
	return timer
}

// function addInfoBrand(key, info, typhoonName) {
// 	if (!graphicLayer) graphicLayer = viewer.graphicLayer;
// 	let bubbleGraphicOpt = new GV.BubbleGraphicOpt();
// 	bubbleGraphicOpt.pointSize = 0;
// 	bubbleGraphicOpt.bindObject = new GV.GeoPoint(Number.parseFloat(info.fLongitude), Number.parseFloat(info.fLatitude));
// 	bubbleGraphicOpt.bubbleType = 'geoBubble';
// 	bubbleGraphicOpt.panelOffset = {
// 		x: 20,
// 		y: -20,
// 	};
// 	let bubble = new GV.BubbleGraphic(bubbleGraphicOpt);
// 	bubble.visible = false;
// 	graphicLayer.add(bubble);
// 	let date = new Date(info.FID.replace(/-/, '/'));
// 	let time = `${date.getFullYear()}年${date.getMonth()}月${date.getDate()}日${date.getHours()}时`;
// 	let r7 = info.radius7 === '' ? `style="display:none"` : `style=""`;
// 	let r10 = info.radius10 === '' ? `style="display:none"` : `style=""`;
// 	let r12 = info.radius12 === '' ? `style="display:none"` : `style=""`;
// 	bubble.panelDom.innerHTML = `
//         <ul class="typhoon">
//             <li><span style="color:#fff;font-size:18px;margin: 0 14px 0 14px;">${typhoonName}</span><span>${time}</span></li>
//             <li><span class="brand-left">中心位置</span><span>${info.fLongitude}° / ${info.fLongitude}°</span></li>
//             <li><span class="brand-left">风速风力</span><span>${info.speed}米/秒,</span><span style="color:red">${info.power}(${info.strong})</span></li>
//             <li><span class="brand-left">中心气压</span><span>${info.pressure}百帕</span></li>
//             <li><span class="brand-left">移速移向</span><span>${info.movespeed}公里/每小时,${info.movedirection}</span></li>
//             <li ${r7}><span class="brand-left">七级半径</span><span>${radiusRange(info.radius7)}</span></li>
//             <li ${r10}><span class="brand-left">十级半径</span><span>${radiusRange(info.radius10)}</span></li>
//             <li ${r12}><span class="brand-left">十二级半径</span><span>${radiusRange(info.radius12)}</span></li>
//         </ul>
//     `;
// 	brandMap.set(key, bubble);
// }

function addLanded(landList) {
	if (typhoonCollection.length === 0) return
	if (!graphicLayer) graphicLayer = viewer.graphicLayer
	for (let land of landList) {
		const billboard = viewer.entities.add({
			position: Cesium.Cartesian3.fromDegrees(land.lng, land.lat),
			billboard: {
				image: '/images/land.svg',
			},
		})
		let bubbleGraphicOpt1 = new GV.BubbleGraphicOpt()
		bubbleGraphicOpt1.pointSize = 0
		bubbleGraphicOpt1.bindObject = new GV.GeoPoint(land.lng, land.lat)
		bubbleGraphicOpt1.bubbleType = 'geoBubble'
		bubbleGraphicOpt1.panelOffset = {
			x: 20,
			y: -20,
		}
		let bubble1 = new GV.BubbleGraphic(bubbleGraphicOpt1)
		graphicLayer.add(bubble1)
		bubble1.panelDom.innerHTML = `<div style="color:#fff;border:solid 1px #2198F4"; font-size:14px;>${land.info}</div>`
		typhoonCollection.push(billboard)
		brandMap.set(land.landaddress, bubble1)
	}
}

// function radiusRange(data) {
// 	let arr = data.split('|').map(Number)
// 	let max = Math.max.apply(null, arr)
// 	let min = Math.min.apply(null, arr)
// 	return `${min}-${max}公里`
// }

function clearAnimation(timer) {
	cancelAnimationFrame(timer)
	addLanded(landList)
}

function destroyed() {
	for (let entry of typhoonCollection) {
		viewer.entities.remove(entry)
	}
	for (let brand of brandMap.values()) {
		graphicLayer.remove(brand)
	}
	viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE)
	typhoonCollection.length = 0
	pointCollection.length = 0
	viewer.clock.multiplier = 1
}
